<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Invoker,负载网络调用组件，底层依懒与网络通信，Invoker主要负责服务调用，自然与路由（比如集群）等功能息息相关，本节先从整体上把控一下Dubbo服务调用体系，服务发现、集群、负载均衡、路由机制等整个知识体系，梳理整理Dubbo Invoker整个类图如下：主要有如下接口群  Invocation(调用上下文环境)   Invocation：1、String getMethodName(">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系">
<meta property="og:url" content="https://www.codingw.net/posts/22a2e460.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="Invoker,负载网络调用组件，底层依懒与网络通信，Invoker主要负责服务调用，自然与路由（比如集群）等功能息息相关，本节先从整体上把控一下Dubbo服务调用体系，服务发现、集群、负载均衡、路由机制等整个知识体系，梳理整理Dubbo Invoker整个类图如下：主要有如下接口群  Invocation(调用上下文环境)   Invocation：1、String getMethodName(">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180610171223710?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/2018061017153961?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-08T14:57:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:14.045Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180610171223710?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/22a2e460.html"/>





  <title>源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/22a2e460.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-08T22:57:01+08:00">
                2020-11-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/22a2e460.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo Invoker概述----服务发现、集群、负载均衡、路由体系">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>Invoker,负载网络调用组件，底层依懒与网络通信，Invoker主要负责服务调用，自然与路由（比如集群）等功能息息相关，本节先从整体上把控一下Dubbo服务调用体系，服务发现、集群、负载均衡、路由机制等整个知识体系，梳理整理Dubbo Invoker整个类图如下：<br><img src="https://img-blog.csdn.net/20180610171223710?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>主要有如下接口群</p>
<ol>
<li>Invocation(调用上下文环境)</li>
</ol>
<ul>
<li>Invocation：<br>1、String getMethodName()    获取调用方法名。<br>2、Class&lt; ? &gt;[] getParameterTypes()    获取被调用方法的参数列表（参数类型）<br>3、Object[] getArguments()    获取被调用方法的参数值数组。<br>4、Map&lt; String, String&gt; getAttachments()    获取附加属性。<br>5、String getAttachment(String key)    根据key获取附加属性值。<br>6、String getAttachment(String key, String defaultValue)    根据key获取附加属性，如果不存在，取默认值。<br>7、Invoker&lt; ?&gt; getInvoker() 获取当前的invoker。</li>
<li>RpcInvocation rpc服务调用实现类<pre><code>Invocation执行调用上下文环境，就是用一个Bean存储当前调用方法的参数，其本质就是一个普通的Bean而已。
</code></pre>
</li>
<li>MockInvocation<pre><code>用于mock单元测试用。
</code></pre>
</li>
<li>DecodeableRpcInvocation 带解码功能的rpc调用上下文<pre><code>该实现主要能从RPC服务调用请求中解析二进制流（二进制包）得到RPC服务调用上下文（方法调用元数据）。
</code></pre>
</li>
</ul>
<span id="more"></span>

<ol start="2">
<li>Invoker 服务调用器，Dubbo中调用服务的抽象。<br>Invoer的抽象接口，继承自com.alibaba.dubbo.common.Node接口</li>
</ol>
<ul>
<li>Node：<br>1、URL getUrl();      获取URL，在dubbo中，注册中心、服务提供者、服务消费者、监控中心等都使用URL描述。<br>2、boolean isAvailable()    ：判断是否可用。<br>3、void destroy()    ：资源销毁。</li>
<li>Invoker:<br>1、Class<T> getInterface()    :获取服务提供者的接口。<br>Result invoke(Invocation invocation) throws RpcException    ：调用服务，返回调用结果。</li>
<li>AbstractInvoker Invoker默认实现（模板类）<br>   该方法主要实现public Result invoke(Invocation inv) throws RpcException,定义执行invoker的基础流程（模板），然后根据不同的实现子类（不同的协议）执行各自个性化的执行任务。其抽象方法：protected abstract Result doInvoke(Invocation invocation) throws Throwable，具体实现将在后文中分析。</li>
<li>DubboInvoker dubbo协议调用器具体实现。</li>
<li>InjvmInvoker injvm协议调用其具体实现（本地协议）</li>
</ul>
<ol start="3">
<li>AbstractClusterInvoker 集群模式调用模板类<br>  该类为Dubbo集群模式的调用模板类，主题解决一个服务服务有多个服务提供者，此时消息消费端在调用服务时如何选择具体的服务提供者。该类需要组织多个服务提供者，并按照指定算法选择一服务提供者进行调用。</li>
</ol>
<ul>
<li>AvailableClusterInvoker<br>通过&lt; dubbo:service cluster = “available” …/&gt; 或 &lt; dubbo:reference cluster=”available” …/&gt;<br>集群策略：总是选择第一个可用的服务提供者。</li>
<li>BroadcastClusterInvoker<br>通过&lt; dubbo:service cluster = “broadcast” …/&gt; 或 &lt; dubbo:reference cluster=”broadcast” …/&gt;<br>集群策略：广播模式，向所有服务提供者都发送请求，任何一个调用失败，则认为失败。</li>
<li>FailbackClusterInvoker<br>通过&lt; dubbo:service cluster = “failback” …/&gt; 或 &lt; dubbo:reference cluster=”failback” …/&gt;<br>集群策略：服务调用失败后，定时重试，重试次数无线次，重试频率：5s。并不会切换服务提供者。</li>
<li>FailfastClusterInvoker<br>通过&lt; dubbo:service cluster = “failfast” …/&gt; 或 &lt; dubbo:reference cluster=”failfast” …/&gt;<br>集群策略：服务调用后，快速失败，直接抛出异常，并不重试，也不受retries参数的制约，适合新增、修改类操作。</li>
<li>FailoverClusterInvoker<br>通过&lt; dubbo:service cluster = “failover” …/&gt; 或 &lt; dubbo:reference cluster=”failover” …/&gt;<br>集群策略：服务调用后，如果出现失败，则重试其他服务提供者，默认重试2次，总共执行3次，重试次数由retries配置，dubbo集群默认方式。</li>
<li>FailsafeClusterInvoker<br>通过&lt; dubbo:service cluster = “failsafe” …/&gt; 或 &lt; dubbo:reference cluster=”failsafe” …/&gt;<br>集群策略：服务调用后，只打印错误日志，然后直接返回。</li>
<li>ForkingClusterInvoker<br>通过&lt; dubbo:service cluster = “forking” …/&gt; 或 &lt; dubbo:reference cluster=”forking” …/&gt;<br>集群策略：并发调用多个服务提供者，取第一个返回的结果。可以通过forks设置并发调用的服务台提供者个数。</li>
</ul>
<p>更多的集群策略，可以参考/dubbo-cluster/src/main/resources/META-/com.alibaba.dubbo.rpc.cluster.Cluster文件。<br><img src="https://img-blog.csdn.net/2018061017153961?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<ol start="4">
<li>LoadBalance 集群负载算法<br>当一个服务有多个服务提供者时，消费端在进行服务调用时选择服务服务提供者的负载均衡算法。<br>LoadBalance定义的接口为：<br>&lt; T&gt; Invoker<T> select(List&lt; Invoker<T>&gt; invokers, URL url, Invocation invocation) throws RpcException;</li>
</ol>
<ul>
<li>ConsistentHashLoadBalance<br>可以通过&lt; dubbo:service loadbalance=”consistenthash” …/&gt;或&lt; dubbo:provider loadbalance = “consistenthash” …/&gt;<br>负载均衡算法：一致性Hash算法，在AbstractClusterInvoker中从多个服务提供者中选择一个服务提供者时被调用。</li>
<li>LeastActiveLoadBalance<br>可以通过&lt; dubbo:service loadbalance=”leastactive” …/&gt;或&lt; dubbo:provider loadbalance = “leastactive” …/&gt;<br>负载均衡算法：最小活跃调用。</li>
<li>RandomLoadBalance<br>可以通过&lt; dubbo:service loadbalance=”random” …/&gt;或&lt; dubbo:service loadbalance = “random” …/&gt;<br>负载均衡算法：随机，如果weight（权重越大，机会越高）</li>
<li>RoundRobinLoadBalance<br>可以通过&lt; dubbo:service loadbalance=”roundrobin” …/&gt;或&lt; dubbo:provider loadbalance = “roundrobin” …/&gt;<br>负载均衡算法：加权轮询算法。</li>
</ul>
<ol start="5">
<li>Directory（目录服务，Invoker的目录服务）<br>该接口主要的作用是服务提供者的目录服务，管理多个服务提供者。</li>
</ol>
<ul>
<li>Directory<br>1、Class&lt; T&gt; getInterface() 获取该服务接口类别。<br>2、List&lt; Invoker&lt; T&gt;&gt; list(Invocation invocation) throws RpcException 根据调用上下文获取当前所有该服务的服务提供者。</li>
</ul>
<p>4.2 AbstractDirectory 目录服务实现的抽象列（模板类）<br>4.3 StaticDirectory 静态目录服务<br>    所谓静态目录服务就是在创建StaticDirectory时指定一个服务提供者集合，则该目录服务实例在其生命周期中，只会返回这些服务提供者。</p>
<ul>
<li>RegistryDirectory 动态目录服务（基于注册中心）、<br>从注册中心动态获取发现服务提供，默认消息消费者并不会指定特定的服务提供者URL，所以会向注册中心订阅服务的服务提供者（监听注册中心providers目录），利用RegistryDirectory自动获取注册中心服务器列表。</li>
</ul>
<ol start="6">
<li>Router 路由功能<br>根据消息消费者URL，结合路由表达式或JS引擎，从Directory中选择符合路由规则的Invoker，再执行负载均衡算法。</li>
</ol>
<ul>
<li>Router<br>1、URL getUrl();    获取消息消费者URL。<br>2、&lt; T&gt; List&lt; Invoker&lt; T&gt;&gt; route(List&lt;  Invoker&lt; T&gt;&gt; invokers, URL url, Invocation invocation) throws RpcException  根据消息消费者URL，从invokers中筛选合适的Invokers。</li>
<li>ConditionRouter 基于条件表达式的路由实现。</li>
<li>ScriptRouter 基于JS引擎的路由实现。</li>
</ul>
<p>单个Invoker的实现，例如DubboInvoker、InJVMInvoker底层调用网络通道发送请求命令（oneway、同步、异步调用方式），其网络底层细节将在后续专门讲解网络实现篇章重点分析，接下来的篇章，主要从源码的角度剖析集群、负载均衡、动态路由目录服务（RegistryDirectory ）的实现细节。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/80b68fd8.html" rel="next" title="源码分析Dubbo服务提供者启动流程-上篇">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo服务提供者启动流程-上篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/62f3002e.html" rel="prev" title="源码分析Dubbo前置篇-寻找注册中心、服务提供者、服务消费者功能入口">
                源码分析Dubbo前置篇-寻找注册中心、服务提供者、服务消费者功能入口 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
